package com.hcms.admin.filter.impl;

import cn.hutool.json.JSONUtil;
import com.hcms.admin.filter.VerificationCodeFilter;
import com.hcms.common.api.CommonResponse;
import com.hcms.common.service.ICaptchaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 * todo
 */
//@Component
public class AdminVerificationCodeFilter implements VerificationCodeFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ICaptchaService captchaService;

    private String loginPath = "/login";
    private String codeKeyName = "codeKey";
    private String codeName = "code";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        logger.info("Run doFilter()");
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            String servletPath = httpRequest.getServletPath();
            logger.info("Servlet path: {}", servletPath);
            if (servletPath.equals(loginPath)) {
                String codeKey = httpRequest.getParameter(codeKeyName);
                String inputCode = httpRequest.getParameter(codeName);
                if (!captchaService.verify(codeKey, inputCode)) {
                    logger.error("The verification code is incorrect");
                    handlerVerificationError(response);
                    return;
                }
                logger.info("Verify successfully");
                captchaService.delete(codeKey);
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 处理验证码错误
     *
     * @param response
     * @throws IOException
     */
    private void handlerVerificationError(ServletResponse response) throws IOException {
        logger.error("Run handlerVerificationError()");
        if (response instanceof HttpServletResponse) {
            logger.error("Verification code error handling");
            CommonResponse<Object> result = new CommonResponse<>(HttpStatus.BAD_REQUEST, "验证码错误");
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.setContentType("application/json");
            httpResponse.setHeader("Access-Control-Allow-Origin", "*");
            httpResponse.setHeader("Cache-Control", "no-cache");
            httpResponse.setStatus(result.getStatus());
            httpResponse.getWriter().println(JSONUtil.parse(result));
            httpResponse.getWriter().flush();
        }
    }

}
